<template>
  <Form class="c-modelPropertyNoCode" :disabled="disabled">
    <Form ref="_batchForm" :labelWidth="90" class="flex">
        <FormItem label="名称列表" style="flex: 1;">
            <fieldCell v-model="batchFormData.nameList"
                :config="{type: 'textarea', clearable: true, rows: 5, placeholder: nameListPlace}" />
        </FormItem>
        <div style="width: 240px;">
            <!-- <div class="flex" style="margin-bottom: -12px;">
                <FormItem label="分割字符" >
                    <fieldCell v-model="batchFormData.split" :config="{type: 'text', clearable: true}" />
                </FormItem>
            </div> -->
            <div >
                <Button @click="onBatchAddClick" class="ivu-ml">添加</Button>
                <Button @click="onBatchResetClick" class="ivu-ml">重置</Button>
                <Button @click="onBatchClear" class="ivu-ml">清空</Button>
            </div>
            <div style="margin-top: 12px;">
                <Button @click="onBatchCopyClick" class="ivu-ml">复制属性</Button>
                <Button @click="onBatchPasteClick" class="ivu-ml">粘贴属性</Button>
            </div>
            <div style="margin-top: 12px;">
                <!-- <Checkbox v-model="hasMoney" class="ivu-ml">有金额</Checkbox> -->
                <!-- <Checkbox v-model="moneyIsAmount" class="ivu-ml">amount</Checkbox> -->
                <Button @click="onBatchTaxClick" class="ivu-ml">添加含税字段</Button>
            </div>
        </div>
    </Form>
    <div class="header flex">
      <span
        v-for="(colItem, colIndex) in columns"
        :key="colIndex"
        :style="{flex: colItem.width ? `0 0 ${colItem.width}px` : '1'}"
        class="col-cell"
      >{{ colItem.title }}</span
    ></div>
    <vuedraggable v-model="value" handle=".num">
    <div
      v-for="(item, index) in value"
      :key="index"
      :class="['col-item flex-middle', errorLine.includes(index) ? 'error' : '']"
    >
      <template v-for="(colItem, colIndex) in columns">
        <span v-if="colItem.key === 'num'" class="col-cell num">{{ index +1 }}</span>
        <span v-else-if="colItem.key === 'option'" class="col-cell option">
          <Button class="btn-add" size="small" @click="addLine(index)">+</Button>
          <Poptip v-if="index >=0" confirm title="是否删除？" @on-ok="removeLine(index)" transfer>
            <Button class="btn-del" size="small">-</Button>
          </Poptip>
        </span>
        <FormItem
          v-else
          :prop="colItem.key"
          :style="{flex: colItem.width ? `0 0 ${colItem.width}px` : '1'}"
          :key="colIndex"
          class="col-cell"
        >
          <fieldCell
            v-model="item[colItem.key]"
            :config="{
                ...colItem,
                type: colItem.key === 'defaultValue' ? (typeObj[item.type] || 'text') : colItem.type,
                options: colItem.key === 'code' ? typeOption[item.type] : colItem.options
            }"
            @change="event => Inputchange(colItem.key, index, event)"
          />
        </FormItem>
      </template>
    </div>
    </vuedraggable>
    <div v-if="!value.length" class="ivu-mt" style="text-align: right;">
        <Button class="btn-add" size="small" @click="addFirstLine">+</Button>
    </div>
    <div class="flex ivu-mt footerwp">
      <Row class="tips flex1">
        <Col :span="8" v-for="item in message" :key="item">{{ item }}</Col>
      </Row>
    </div>
  </Form>
</template>

<script>
import { typeOptionAll, batchConfig } from './config';
import dayjs from "dayjs";
import vuedraggable from "vuedraggable"

export default {
    components: {vuedraggable},
    data() {
        return {
            curIndex: '0',
            message: [],
            errorLine: [],
            timer: 0,
            typeObj: { String: 'text',Double: 'number',Integer: 'number',Boolean: 'check',DateTime: 'datetime'},
            showFieldList: false,
            propertiesObject: this.$modelObject.getClass('propertiesNoGroup'),
            nameListPlace: batchConfig.nameListPlace,
            hasMoney: true,
            moneyIsAmount: false,
            batchFormData: {
                nameList: '',
                commentList: '',
                split: '',
                disNumber: 6
            }
        }
    },
    model: {
        prop: 'value',
        event: 'change'
    },
    props: {
        classObject: {
            default() {
                return null
            }
        },
        value: {
            default() {
                return []
            }
        },
        disabled: {
            default() { return false }
        },
        featuresHaveCode: {
            default() {
                return false
            }
        }
    },
    watch: {
        value(val) {
            // console.log("🚀 ~ file: cfgModelPropertyNoGroup.vue:90 ~ value ~ val:", val)
        }
    },
    methods: {
        // 校验：name是否有重复
        checkName() {
            let message = {}
            this.message = []
            this.errorLine = []
            this.value.forEach((item, index) => {
                if (item.name) {
                    let key = item.name;
                    let arrFilter = this.value.filter(
                        (fItem, fIndex) => fItem.name === item.name && index != fIndex
                    )
                    if (arrFilter.length > 0) {
                        this.errorLine.push(index)
                        if (message[key]) {
                            message[key].push(index + 1)
                        } else {
                            message[key] = [index + 1]
                        }
                    }
                }
            })

            message = Object.keys(message).map(key => {
                return `num ${message[key].join('、')}, ${this.lang.sameName}`
            })
            this.message = message
            return !this.message.length;
        },
        formatDate(val) {
            return dayjs(val).format('YYYY-MM-DD HH:mm:ss')
        },
        checkValues() {
            if (!this.checkName()) {
                return false
            }
            
            let res = this.value.map(item => {
                return {
                    ...item,
                    defaultValue: item.type==='DateTime' ? this.formatDate(item.defaultValue) : item.defaultValue,
                }
            })
            return res;
        },
        addFirstLine() {
            this.value.push(this.propertiesObject.tpl())
            this.change()
        },
        addLine(index) {
            this.value.splice(index+1, 0, this.propertiesObject.tpl())
            this.change()
        },
        removeLine(index) {
            this.value.splice(index, 1)
            this.change()
        },
        Inputchange(key, index) {
            if (key==='type') {
                this.value[index].defaultValue = null
                this.change()
            }
        },
        addMessage(text) {
            clearTimeout(this.timer)
            this.message = text
            this.timer = setTimeout(() => {
                this.message = ''
            }, 3000);
        },
        change() {
            this.$emit('change', this.value)
        },
        filterOption(selectArr, type) {
            if (selectArr.length) {
                return typeOptionAll[type]
                    ? typeOptionAll[type].map(item => ({...item, disabled: selectArr.includes(item.value)} ))
                    : []
            } else {
                return typeOptionAll[type]
            }
        },
        // 根据excel复制的内容，批量添加属性
        onBatchAddClick() {
            if (this.batchFormData.nameList) {
                let nameList = this.batchFormData.nameList.split('\n')
                let valueList = []

                this.value.forEach(item => item.name && valueList.push(item.name))
                nameList.forEach((item, index) => {
                    if (!!item) {
                        let itemArr = item.split('\t')
                        let name = itemArr[0]
                        if (!valueList.includes(name)) {
                            let comments = itemArr.length > 2 ? itemArr[2] : itemArr[1]
                            let type = itemArr.length > 2 ? itemArr[1] : batchConfig.calcType(comments)
                            let newItem = {
                                ...this.propertiesObject.tpl(),
                                type: batchConfig.typeMap[type] || 'String',
                                name,
                                comments
                            }

                            if (index === 0 && !this.value[0].name) {
                                this.value.splice(0, 1, newItem)
                            } else {
                                this.value.push(newItem)
                            }
                            // index++
                        }
                    }
                })
            }
        },
        onBatchTaxClick() {
            let taxFields = batchConfig.taxFields(this.hasMoney, this.moneyIsAmount)
            
            // 先删除已有的字段
            taxFields.forEach(item => {
                let index = this.value.findIndex(vItem => vItem.name === item.name)
                if (index !== -1) {
                    this.value.splice(index, 1)
                }
            })
            let insertIndex = this.value.findIndex(vItem => vItem.name === 'quantity');
            
            console.log("file: cfgModelPropertyNoGroup.vue:251  onBatchTaxClick", this.value, insertIndex)
            taxFields.forEach(item => {
                (insertIndex !== -1) ? this.value.splice(insertIndex+1, 0, item) && insertIndex++ : this.value.push(item)
            })
        },
        onBatchResetClick() {
            this.$refs._batchForm.resetFields()
        },
        onBatchClear() {
            this.value.length = 0
            this.value.push(this.propertiesObject.tpl())
        },
        onBatchCopyClick() {
            localStorage.setItem('_batchCopy_modelProperties', JSON.stringify(this.value,null,4))
        },
        onBatchPasteClick() {
            let copyValue = localStorage.getItem('_batchCopy_modelProperties')

            if (copyValue) {
                JSON.parse(copyValue).forEach(item => {
                    let {group, ...otherItem} = item
                    this.value.push(otherItem)
                })
            }
        },
    },
    computed: {
        typeOption() {
            let selectArr = []
            if (!this.featuresHaveCode) return {}
            this.value.map(item => {
                item.code && selectArr.push(item.code)
            })

            let res = {
                String: this.filterOption(selectArr, 'String'),
                Double: this.filterOption(selectArr, 'Double'),
                Integer: this.filterOption(selectArr, 'Integer'),
                Boolean: this.filterOption(selectArr, 'Boolean'),
                DateTime: this.filterOption(selectArr, 'DateTime'),
            }
            !this.showFieldList && (this.showFieldList = true)
            return res;
        },
        lang() {
            return {
                "en-US": {
                    String: 'String',
                    Double: 'Double',
                    Integer: 'Integer',
                    Boolean: 'Boolean',
                    DateTime: 'DateTime',
                    num: 'number',
                    name: 'name',
                    type: 'type',
                    defaultValue: 'defaultValue',
                    comments: 'comments',
                    canQuery: 'can query',
                    option: 'option',
                    sameName: 'same name',
                    typeUnequal: 'Same name, but different type',
                },
                "zh-CN": {
                    String: '字符',
                    Double: '浮点',
                    Integer: '整型',
                    Boolean: '布尔',
                    DateTime: '时间',
                    num: '序号',
                    name: '名称',
                    type: '类型',
                    defaultValue: '默认值',
                    comments: '备注',
                    canQuery: '可查询',
                    option: '操作',
                    sameName: '名称相同',
                    typeUnequal: '名称相同, 但是类型不同',
                },
            }[this.G_Locale];
        },
        columns() {
            let res = [
                { key: 'num', title: this.lang.num, width: 50 },
                { key: 'name', type: 'text', clearable: true, title: this.lang.name },
                { key: 'type', type: 'select', width: 80, title: this.lang.type,
                    options: [
                        {label: this.lang.String, value: 'String'},
                        {label: this.lang.Double, value: 'Double'},
                        {label: this.lang.Integer, value: 'Integer'},
                        {label: this.lang.Boolean, value: 'Boolean'},
                        {label: this.lang.DateTime, value: 'DateTime'}
                    ]
                },
                { key: 'defaultValue', type: 'text', clearable: true, title: this.lang.defaultValue },
                { key: 'comments', type: 'text', clearable: true, title: this.lang.comments },
                { key: 'option',  width: 60, type: 'text', title: this.lang.option },
            ]
            if (this.featuresHaveCode) {
                res.splice(5, 0, { key: 'code',  width: 100, type: 'select', title: this.lang.canQuery, clearable: true})
            }
            return res;
        }
    }
}
</script>

<style scoped lang="less">
.c-modelPropertyNoCode {
    padding: 6px 0;
    background-color: #fff;
    .ivu-collapse-header {
        display: flex;
        align-items: center;
    }
    /deep/ .ivu-collapse-header {
        display: flex;
        align-items: center;
    }
}
.tips {
    margin-left: 30px;
    line-height: 30px;
    color: red;
}
// 列表相关
.header {
    background-color: #f7f7f7;
    .col-cell {
        line-height: 34px;
        border: none;
        border-radius: 0;
    }
}
.col-item {
    margin: 6px 0;
    .option {
        flex: 0 0 60px;
        padding-left: 6px;
        border: none;
        text-align: left;
        .ivu-btn + .ivu-poptip {
            margin-left: 8px;
        }
    }
    .num {
        line-height: 32px;
        flex: 0 0 50px;
        text-align: center;
        background-color: #f7f7f7;
        cursor: move;
    }
    &.error {
        .num {
            border: 1px solid red;
        }
    }
}
.col-cell {
    flex: 1;
    text-align: center;
    // border: 1px solid #dcdee2;
    border-radius: 4px;
    margin: 0;
    + .col-cell {
        margin-left: 6px;
    }
}
</style>
